package com.zl.autocode.common.utils.generator.util;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.hutool.core.util.StrUtil;

public class JavaTypeConvert {

    // 默认：：JDBC类型，JAVA类型全称，JAVA类型,扩展类型，是否标准类型0否，1是
    private static String[] DEFAULT_TYPE = {"VARCHAR", "java.lang.String","String", "String","1"};
    /** 
     * 转换字段类型，开始字符串匹配
     * designType : 数据库字段类型
     * mapping : 映射关系
     */
    public static String[] convertByPrefix(String databaseType, String designType, Map<String, String[]> mapping) {
        String[] typeArr = DEFAULT_TYPE;
        if (StrUtil.isBlank(designType)) {
            return typeArr;
        }
        
        String dt = designType.toLowerCase();
        for (Map.Entry<String, String[]> entry : mapping.entrySet()) {
            String mapKey = entry.getKey().toLowerCase();
            String[] mapValue = entry.getValue();
            if(mapKey.length() <= designType.length() && dt.startsWith(mapKey)){
                typeArr = mapValue;
                break;
            }else if(databaseType.equalsIgnoreCase(mapValue[2])){
                typeArr = mapValue;
                break;
            }
        }
        
        return typeArr;
    }

    /** 
     * 转换字段类型，正则匹配
     * designType : 数据库字段类型
     * mapping : 映射关系
     */
    public static String[] convertByPattern(String databaseType, String designType, Map<String, String[]> mapping) {
        String[] typeArr = DEFAULT_TYPE;
        if (StrUtil.isBlank(designType)) {
            return typeArr;
        }
        
        String dt = designType.toLowerCase();
        for (Map.Entry<String, String[]> entry : mapping.entrySet()) {
            String mapKey = entry.getKey().toLowerCase();
            String[] mapValue = entry.getValue();
            
            Pattern p = Pattern.compile(mapKey, Pattern.CASE_INSENSITIVE);
            Matcher m = p.matcher(dt);
            if (m.find()) {
                typeArr = mapValue;
                break;
            }else if(databaseType.equalsIgnoreCase(mapValue[2])){
                typeArr = mapValue;
                break;
            }
        }
        
        return typeArr;
    }

}